﻿using FS_Service;
using FS_Unitys.Basic;
using FS_Unitys.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace FileWatch.Controllers.Api
{
    /// <summary>
    //
    /// </summary>
    [RoutePrefix("api/PullFile")]
    public class PullFileController : ApiController
    {
        private FileTransferWebservice.TD_WebService service = new FileTransferWebservice.TD_WebService();
        private FSService FSService = new FSService();
      //  private static readonly LogHelper logHelper = new LogHelper(typeof(PullFileController));

        /// <summary>
        /// 从体检服务器读取数据到前置机写入
        /// </summary>
        /// <returns></returns>
        [HttpGet,Route("InnerReadToOutWrite")]
        public ResultInfo InnerReadToOutWrite()
        {
            // 从远程读取
            string result = service.ReadNetWorkToAbsolute();
            ResultInfo res = JsonXmlUtils.DeserializeObject<ResultInfo>(result);
            if (res.code != CodeStatus.success.GetHashCode())
                return res;

            string resJson = JsonXmlUtils.SerializeObject(res);
            res = FSService.WriteAbsoultePath(resJson);
            if (res.code != CodeStatus.success.GetHashCode())
                return res;


            List<string> listFileName = res.data as List<string>;
            string data = JsonXmlUtils.SerializeObject(listFileName);
         //   logHelper.Info("文件改名:" + data);

            // 调用webservice告知已经搬运完，修改文件名
            result = service.ReNameNetWork(data);

            return JsonXmlUtils.DeserializeObject<ResultInfo>(result);
        }

        /// <summary>
        /// 从前置机读取数据通过共享文件夹写入到体检服务器
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("OutReadToInnerWrite")]
        public ResultInfo OutReadToInnerWrite()
        {
            // 本地读
            ResultInfo res = FSService.ReadToAbsolute();
            if (res.code != CodeStatus.success.GetHashCode())
                return res;

            string resJson = JsonXmlUtils.SerializeObject(res);
         //   logHelper.Info(resJson);
            // 写入共享文件夹
            string result = service.WriteNetWorkPath(resJson);
            res = JsonXmlUtils.DeserializeObject<ResultInfo>(result);
            if (res.code != CodeStatus.success.GetHashCode())
                return res;

            // 修改本地文件名称
            List<string> listDirFileName = JsonXmlUtils.DeserializeObject<List<string>>(res.data.ToString());

           // logHelper.Info($"本地文件名:{JsonXmlUtils.SerializeObject(listDirFileName)}");
            // 修改本地名
            res = FSService.RenameFileNameSuffix(listDirFileName, false);
            return res; 
        }
    }
}
